package com.hsogoo.ultraman.listener;

import com.hsogoo.ultraman.container.ConfigContainer;
import com.hsogoo.ultraman.event.ConfigChangeEvent;
import com.hsogoo.ultraman.spring.refreshable.RefreshableConfig;
import com.hsogoo.ultraman.spring.refreshable.RefreshableConfigRegistry;
import com.hsogoo.ultraman.utils.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.env.Environment;

import java.util.Collection;
import java.util.Set;

@Slf4j
public class AutoRefreshConfigChangeListener implements ConfigChangeListener {

    private Environment environment;
    private BeanFactory beanFactory;
    private RefreshableConfigRegistry refreshableConfigRegistry;

    public AutoRefreshConfigChangeListener(Environment environment, BeanFactory beanFactory){
        this.environment = environment;
        this.beanFactory = beanFactory;
        this.refreshableConfigRegistry = ConfigContainer.getBean(RefreshableConfigRegistry.class);
    }

    @Override
    public void onChange(ConfigChangeEvent changeEvent) {
        log.info("Config上添加的AutoRefreshConfigChangeListener.onChange===[{}]", changeEvent);
        log.info("这里做bean属性的动态刷新。。。");
        Set<String> keys = changeEvent.changedKeys();
        if (CollectionUtils.isEmpty(keys)) {
            return;
        }
        for (String key : keys) {
            log.info("要刷新的key=[{}] ", key);
            log.info("要刷新的旧的value=[{}] ", changeEvent.getChange(key).getOldValue());
            log.info("要刷新的新的value=[{}] ", changeEvent.getChange(key).getNewValue());
            // 更新配置
            Collection<RefreshableConfig> targetValues = refreshableConfigRegistry.get(key);
            for(RefreshableConfig refreshableConfig : targetValues){
                //先只实现简单的String类型的替换
                try {
                    refreshableConfig.refresh(changeEvent.getChange(key).getNewValue());
                } catch (Exception e) {
                    log.error("refresh config value failed, {}", refreshableConfig, ExceptionUtil.getDetailMessage(e));
                }
            }
        }
    }

}
